package com.windoent.yugioh;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.baidu.mobstat.StatService;
import com.mob.MobSDK;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.utils.Base64Utils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.RSAUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author : robert
 * date   : 2021/4/26 14:13
 * desc   :
 */
public class MyApplication extends MultiDexApplication {
    @SuppressLint("StaticFieldLeak")
    private static MyApplication instance;
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;
    public static String cityCode = "";//选择城市码
    public static String slectShai = "";//筛选
    public static int refreeType = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mContext = this;
        //第三方库初始化
        thirdLibInit();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    //第三方库初始化
    private void thirdLibInit() {
        //Toastutils初始化
        ToastUtils.init(mContext);
        //处理崩溃
        ereza();
        //ushare友盟
        ushare();
        //okhttputils
        okHttpUtilsInit();
        //onkeyshare
        onekeyshare();
        //bugly
        bugly();
        //百度统计
        baiduTJ();
    }

    //百度统计
    private void baiduTJ() {
        StatService.setAuthorizedState(mContext, true);
        StatService.autoTrace(mContext, true, true);
    }

    private void bugly() {
        //增加上报进程控制
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, "cde9c6bcbf", BuildConfig.LOG_DEBUG, strategy);
    }

    private void onekeyshare() {
        MobSDK.submitPolicyGrantResult(true, null);
        MobSDK.init(mContext);
    }


    //QQ微信分享等陆
    private void ushare() {
        UMConfigure.init(this, "608a18edf00c2e19b93f0799"
                , "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        // 微信设置
        PlatformConfig.setWeixin("wxda7a8e509397a8b1", "d84b2f774508fc2f9613a6ea86e5f14a");
        PlatformConfig.setWXFileProvider("com.windoent.yugioh.fileprovider");
        // QQ设置
        PlatformConfig.setQQZone("1111483891", "xD5bTurqPpOdEaoE");
        PlatformConfig.setQQFileProvider("com.windoent.yugioh.fileprovider");
    }

    private void okHttpUtilsInit() {
        try {
            InputStream in = getAssets().open("private.pem");
            PrivateKey privateKey = RSAUtils.loadPrivateKey(in);
            byte[] bytes = Constants.rsaPrivateString.getBytes();
            byte[] decryptByte = RSAUtils.encryptData(bytes, privateKey);
            String encryptString = Base64Utils.encode(decryptByte);
//            byte[] encryptPrivate = RSAUtils.encryptPrivateByte(bytes, Constants.rsaPrivateKey);
//            String encryptString = new String(encryptPrivate);
            LogUtils.d("encryptString-->:" + encryptString);
            String decryptStr = new String(decryptByte);
            //网络请求初始化
            CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .cookieJar(cookieJar)
                    .cache(null)
                    .connectTimeout(5, TimeUnit.SECONDS)//5s超时时间
                    .readTimeout(5, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .addInterceptor(new LoggerInterceptor("android_client"))
                    //其他配置
                    .addNetworkInterceptor(new Interceptor() {//自定义拦截器
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
                            //配置统一的头
                            Request.Builder builder = request.newBuilder();
                            Request newRequest = builder
                                    .addHeader("platform", "Android")
                                    .addHeader("signature", encryptString)
                                    .build();
                            return chain.proceed(newRequest);
                        }
                    })
                    .build();

            OkHttpUtils.initClient(okHttpClient);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.d("encryptString-->" + e.getMessage());
        }
    }

    @SuppressLint("RestrictedApi")
    private void ereza() {
        CustomActivityOnCrash.install(mContext);
    }

    public synchronized static MyApplication getInstance() {
        return instance;
    }

    public static Context getmContext() {
        return mContext;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }


    //---保存信息到配置文件---
    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public String getProperty(String key) {
        String res = AppConfig.getAppConfig(this).get(key);
        return res;
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    private void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }

    public void cleanLoginInfo() {
        removeProperty("user");
    }

    /**
     * 保存登录信息
     */
    @SuppressWarnings("serial")
    public void saveUserInfo(String string) {
        setProperties(new Properties() {
            {
                setProperty("user", string);
            }
        });
    }

    /**
     * 获得登录用户的信息
     *
     * @return
     */
    public String getUserInfo() {
        return getProperty("user");
    }

    public void cleanMsgNumber() {
        removeProperty("msgNumber");
    }

    /**
     * 信息数量
     */
    @SuppressWarnings("serial")
    public void saveMsgNumber(String string) {
        setProperties(new Properties() {
            {
                setProperty("msgNumber", string);
            }
        });
    }

    /**
     * 信息数量
     *
     * @return
     */
    public String getMsgNumber() {
        return getProperty("msgNumber");
    }

}
